/* eslint-disable require-await */
/* eslint-disable no-useless-constructor */
/* eslint-disable no-empty-function */
import {
  Connection, Channel, connect, Message, Replies
} from 'amqplib';
import { QUEUE, EVENT, EXCHANGE } from './constants';
import { io } from '../app';
import { AppController } from '../controllers/app.controller';

class RabbitMQ {
  private conn: Connection;

  private channel: Channel;

  private  queue: Replies.AssertQueue;

  constructor(private options: any) {}

  // 连接
  async start(): Promise<void> {
    this.conn = await connect(this.options);
    this.channel = await this.conn.createChannel();
  }

  // 建立queue, 并绑定交换机
  async assertQueue(): Promise<void> {
    this.queue = await this.channel.assertQueue(QUEUE.newTask, {
      durable: false,
    });
  }

  // 创建交换机
  async assertExchange(): Promise<void> {
    await this.channel.assertExchange(EXCHANGE.name, EXCHANGE.type );
  }
  // 绑定交换机
  async bindQueue(): Promise<void> {
    await this.channel.bindQueue(this.queue.queue, EXCHANGE.name, EXCHANGE.routingKey)
  }

  // 向queue发布消息
  async publishInQueue(queue: string, message: any, priority?: number) {
    await this.channel.sendToQueue(queue, Buffer.from(message), { priority });
  }

  // 在exchange中向channel发布消息
  async publishInExchange(
    exchange: string,
    routingKey: string,
    message: string
  ): Promise<boolean> {
    return this.channel.publish(exchange, routingKey, Buffer.from(message));
  }

  // 
  async consume(queue: string): Promise<Message> {
    return new Promise<Message>(((resolve) => {
      try {
        this.channel.consume(queue, async (message: any) => {
          if(message && message.content){
            const randomSocketId = AppController.randomId(AppController.getCustomerServiceUsers());
            // const content = JSON.parse(message.content.toString());
            io.to(randomSocketId).emit(EVENT.taskAssignment, message.content.toString());
            console.log('----------consume message', message.content.toString())
            resolve(message);
            // this.channel.ack(message);
            // this.closeChannel();
          }
        },{
          noAck: true //自动确认消息被消费
          });
      } catch (error) {
        console.log('err', error)
      }
      
    }));
  }

  // 获取queue中收到的消息
  async getQueueInfo(): Promise<any> {
    return this.channel.checkQueue(QUEUE.newTask);
  }

  async closeChannel() {
    await this.channel.close();
  }
}

export { RabbitMQ };
